package common;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JComponent;
import javax.swing.JFormattedTextField;

import db.DBConnection;
import db.DBInteraction;

public class KeyFilterJListener implements KeyListener {

	private static String query = "SELECT Nome FROM Comune WHERE Nome LIKE ?";
	private String previousDigits = "";
	private DBConnection dbCon;
	private JFormattedTextField comp;
	private String temp;
	
	public KeyFilterJListener(JFormattedTextField comp) 
	{
		this.comp = comp;
		try {
			dbCon = new DBConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub
		if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE && previousDigits.getBytes().length > 1)
			previousDigits = (previousDigits.subSequence(0, previousDigits.length()-1)).toString();
		else
		{
			temp = "";
			temp += e.getKeyChar();
			previousDigits += temp.toUpperCase();
		
			System.out.println("Premuto tasto: " + e.getKeyChar());
			ResultSet res = DBInteraction.executeParametricQuerySingleParameter(dbCon, query, previousDigits+"%");
			try {
				while(res.next())
				{
					comp.setText(res.getString(1));
				}
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

}
